//
//  QWebViewVC.m
//  QoilPublic
//
//  Created by 杨凯 on 16/7/5.
//  Copyright © 2016年 杨凯. All rights reserved.
//

#import "QWebViewVC.h"
#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
@interface QWebViewVC ()<UIWebViewDelegate>

@property (nonatomic, strong) UIWebView *webView;

@end

@implementation QWebViewVC

- (void)dealloc{
    CLog(@"销毁了");
}
- (id)init{
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.webView];
    [self setupForDismissKeyboard];//释放键盘
    
    /*UIButton *shareBtn = [QViewUtility createButtonWithFrame:CGRectMake(0, kScreenHeight-50, kScreenWidth, 50) font:17 title:@"分享" titleColor:[UIColor whiteColor] backgroundColor:[QColorUtility defaultBlueColor]];
     [shareBtn blueStyle];
     [shareBtn addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
     [self.view addSubview:shareBtn];*/
    if(_style == WebLocalityStyle){
        
    }else{
        
        NSString *str = @"http://www.ydaol.com/oilWX_api/coverDriverInfo/operatorAlliance.html";
        
        if ([self.url isEqualToString:str]) {
            
        }else{
            
            [self addRightBtn];
        }
        
    }
    
    [self requestData];
}

- (void)addRightBtn {
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(shareAction)];
    [rightBarItem setTintColor:[UIColor whiteColor]];
    self.navigationItem.rightBarButtonItem = rightBarItem;
}

- (void)requestData{
    
    if(_style == WebLocalityStyle){
        NSString *filePath = [[NSBundle mainBundle]pathForResource:@"law" ofType:@"html"];
        [_webView loadHTMLString:[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil] baseURL:[NSURL URLWithString:filePath]];
    }else if (_style == WebNetWorkStyle){
        
        NSString *newUrls = [NSString stringWithFormat:@"%@?token=%@",self.url,[QUserInfo sharedInfo].loginModel.token];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:newUrls]];
        
        [_webView loadRequest:request];
    }
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    
    [QViewUtility showMBHudToView:self.view hideBg:NO];
}


#pragma mark - Getter/Setter
- (UIWebView*)webView {
    if (!_webView) {
        _webView = [UIWebView new];
        NSString *version = [UIDevice currentDevice].systemVersion;
         _webView.delegate = self;
        if (version.doubleValue >= 11.0) {
            
            _webView.frame = CGRectMake(0, kNavHeight+kStatusHeight, kScreenWidth, kScreenHeight-kNavHeight-kStatusHeight);
            
        }else{
            
             _webView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        }
        
       
       
        
    }
    
    return _webView;
}

- (void)shareAction{
    
    
    [UMSocialData defaultData].extConfig.wechatTimelineData.title = self.title;
    [UMSocialData defaultData].extConfig.wechatTimelineData.url = _url;
    
    [UMSocialData defaultData].extConfig.wechatSessionData.title = self.title;
    [UMSocialData defaultData].extConfig.wechatSessionData.url = _url;
    
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:UmengKey
                                      shareText:self.title
                                     shareImage:[UIImage imageNamed:@"loginlogo_image"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToWechatTimeline,UMShareToWechatSession,nil]
                                       delegate:nil];
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [QViewUtility hideMBHudToView:self.view];
    self.context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.context.exceptionHandler = // 打印异常
    ^(JSContext *context, JSValue *exceptionValue)
    {
        context.exception = exceptionValue;
        CLog(@"%@", exceptionValue);
    };
    
    __weak QWebViewVC *wSelf = self;
    
    self.context[@"myShare"] =^(){
        __strong QWebViewVC *sSelf = wSelf;
        NSLog(@"完成");
        NSLog(@"+++++++Begin Log+++++++");
        NSArray *args = [JSContext currentArguments];
        NSString *str = @"";
        for (JSValue *jsVal in args) {
            NSLog(@"%@", jsVal);
            str = [NSString stringWithFormat:@"%@",jsVal];
        }
        [sSelf myShare:str];
        JSValue *this = [JSContext currentThis];
        NSLog(@"this: %@",this);
        NSLog(@"-------End Log-------");
    };
    self.context[@"shareCircleFriends"] =^(){
        __strong QWebViewVC *sSelf = wSelf;
        NSLog(@"完成");
        NSLog(@"+++++++Begin Log+++++++");
        NSArray *args = [JSContext currentArguments];
        NSString *str = @"";
        for (JSValue *jsVal in args) {
            NSLog(@"%@", jsVal);
            str = [NSString stringWithFormat:@"%@",jsVal];
        }
        [sSelf myShare1:str];
        JSValue *this = [JSContext currentThis];
        NSLog(@"this: %@",this);
        NSLog(@"-------End Log-------");
    };
}
//分享微信
- (void)myShare:(NSString *)callString{
    NSLog(@"Get:%@", callString);
    // 成功回调JavaScript的方法Callback
    NSDictionary *dic = [self parseJSONStringToNSDictionary:callString];
    
    [UMSocialData defaultData].extConfig.wechatSessionData.title = dic[@"title"];
    [UMSocialData defaultData].extConfig.wechatSessionData.url = dic[@"url"];
    NSString *content = [dic objectForKey:@"digest"];
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatSession] content:content image:[UIImage imageNamed:@"loginlogo_image"] location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            CLog(@"分享成功！");
        }
    }];
}
//分享朋友圈
- (void)myShare1:(NSString *)callString{
    NSLog(@"Get:%@", callString);
    // 成功回调JavaScript的方法Callback
    NSDictionary *dic = [self parseJSONStringToNSDictionary:callString];
    
    [UMSocialData defaultData].extConfig.wechatTimelineData.title = dic[@"title"];
    [UMSocialData defaultData].extConfig.wechatTimelineData.url = dic[@"htmlUrl"];
    NSString *content = [dic objectForKey:@"digest"];
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatTimeline] content:content image:[UIImage imageNamed:@"loginlogo_image"] location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            CLog(@"分享成功！");
        }
    }];
}

-(NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
    return responseJSON;
}

@end
